import React from 'react';
import {connect} from 'dva/index';
import {Button, Col, Form, Input, InputNumber, message, Radio, Row, Table, Tabs} from 'antd';
import SingleDragger from "../../commons/SingleDragger";
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
const RadioGroup = Radio.Group;
const R = require("ramda");


const lgOdDeclare = Form.create()(class LgOdDeclare extends React.Component {
    constructor(props) {
        super(props);
        let normalDeclareExt = this.props.logisticsOrder.dataSource.declare && this.props.logisticsOrder.dataSource.declare.normalDeclareExt ?
            this.props.logisticsOrder.dataSource.declare.normalDeclareExt : [];
        if(normalDeclareExt && normalDeclareExt.length > 0){
            normalDeclareExt = JSON.parse(normalDeclareExt);
            normalDeclareExt.map(item => item.id = this.count++);
        }
        let payDeclareExt= this.props.logisticsOrder.dataSource.declare && this.props.logisticsOrder.dataSource.declare.payDeclareExt ?
            this.props.logisticsOrder.dataSource.declare.payDeclareExt : [];
        if(payDeclareExt && payDeclareExt.length > 0){
            payDeclareExt = JSON.parse(payDeclareExt);
            payDeclareExt.map(item => item.id = this.payCount++);
        }

        this.state = {
            normalDeclareExt,
            defaultNormalDeclareList: R.clone(normalDeclareExt),
            payDeclareExt,
            defaultPayDeclareList: R.clone(payDeclareExt)
        };
    }

    count = 1;
    payCount = 1;
    componentWillReceiveProps(nextProps) {
        let dataSource = this.props.logisticsOrder.dataSource.declare ? this.props.logisticsOrder.dataSource.declare : {};
        let nextDataSource = nextProps.logisticsOrder.dataSource.declare ? nextProps.logisticsOrder.dataSource.declare : {};
        if (!R.equals(dataSource.normalDeclareExt)(nextDataSource.normalDeclareExt)) {
            let normalDeclareExt = nextDataSource.normalDeclareExt ? nextDataSource.normalDeclareExt : [];
            if(normalDeclareExt && normalDeclareExt.length > 0){
                normalDeclareExt = JSON.parse(normalDeclareExt);
                normalDeclareExt.map(item => item.id = this.count++);
            }
            this.setState({ normalDeclareExt, defaultNormalDeclareList: R.clone(normalDeclareExt) });
        }
        if (!R.equals(dataSource.payDeclareExt)(nextDataSource.payDeclareExt)) {
            let payDeclareExt = nextDataSource.payDeclareExt ? nextDataSource.payDeclareExt : [];
            if(payDeclareExt && payDeclareExt.length > 0){
                payDeclareExt = JSON.parse(payDeclareExt);
                payDeclareExt.map(item => item.id = this.payCount++);
            }
            this.setState({ payDeclareExt, defaultPayDeclareList: R.clone(payDeclareExt) });
        }
    }

    handleResetFields = () => {
        this.setState({
            normalDeclareExt: this.state.defaultNormalDeclareList,
            payDeclareExt: this.state.defaultPayDeclareList
        });
        this.props.form.resetFields();
    }


    handleConfirm = () => {
        this.props.form.validateFields({ force: true }, (errors, values) => {
            if (errors) return;
            let dataSource = this.props.logisticsOrder.dataSource.declare ? this.props.logisticsOrder.dataSource.declare : {};

            let  flag = true;
            let normalDeclareExt = R.clone(this.state.normalDeclareExt ? this.state.normalDeclareExt : []);
            let payDeclareExt = R.clone(this.state.payDeclareExt ? this.state.payDeclareExt : []);
            normalDeclareExt.map(item => {
                if (!item.company || !item.weight || !item.count) flag = false;
                else item.id = undefined
            });
            payDeclareExt.map(item => {
                if (!item.weight || !item.count) flag = false;
                else item.id = undefined
            });
            if (!flag) message.error("正常单报关或买单报关信息不完整！");

            values.id = dataSource.id;
            values.normalDeclareExt = JSON.stringify(normalDeclareExt);
            values.payDeclareExt = JSON.stringify(payDeclareExt);
            values.declareBillUrl = this.refs.declareBillUrl.getUrl();
            values.passNoticeUrl = this.refs.passNoticeUrl.getUrl();
            values.otherUrl = this.refs.otherUrl.getUrl();

            if (!R.equals(R.pick(Object.keys(values), dataSource), values)) {
                this.props.dispatch({
                    type: "logisticsOrder/updateOdDeclare",
                    payload: {
                        ...values,
                        onSuccess: ()=>{ this.props.handleCancel(); },
                        onFail: ()=>{ this.props.handleCancel(); }
                    },
                });
            }else {
                message.info("您未修改任何报关信息！");
                //this.props.handleCancel();
            }
        })
    }

    refreshInput = (id, prop, e) => {
        this.refreshInputNumber(id, prop, 'normal', e.target.value);
    }

    refreshInputNumber = (id, prop, type, e) => {
        let normalDeclareExt = this.state.normalDeclareExt;
        let payDeclareExt = this.state.payDeclareExt;
        if(type == 'normal'){
            normalDeclareExt.map(item => { if (item.id === id) item[prop] = e });
        }
        if(type == 'pay'){
            payDeclareExt.map(item => { if (item.id === id) item[prop] = e });
        }
        this.setState(normalDeclareExt, payDeclareExt);
    }

    onDelete = (id, type) => {
        let normalDeclareExt = this.state.normalDeclareExt;
        let payDeclareExt = this.state.payDeclareExt;
        if(type == "normal"){
            normalDeclareExt.splice(normalDeclareExt.findIndex(item => item.id === id), 1);
        }
        if(type == "pay"){
            payDeclareExt.splice(payDeclareExt.findIndex(item => item.id === id), 1);
        }
        this.setState({normalDeclareExt, payDeclareExt});
    }

    onAdd = (type) => {
        let normalDeclareExt = this.state.normalDeclareExt;
        let payDeclareExt = this.state.payDeclareExt;
        if(type == "normal"){
            normalDeclareExt.push({ id: this.count++ });
        }
        if(type == "pay"){
            payDeclareExt.push({ id: this.payCount++ });
        }
        this.setState({normalDeclareExt, payDeclareExt});
    }

    getNormalColumns = (disabled) => {
        let normalColumns = [
            {
                title: '经营单位', dataIndex: 'company', key: 'company', width: disabled ? '50%' : '40%',
                render: (text, record, index) => {
                    if (disabled) return <span>{record.company}</span>
                    else return <Input maxLength="50" value={record.company} style={{ width: '100%' }} onChange={this.refreshInput.bind(this, record.id, 'company')} />
                }
            },
            {
                title: '重量(KGS)', dataIndex: 'weight', key: 'weight', width: '25%',
                render: (text, record, index) => {
                    if (disabled) return <span>{record.weight}</span>
                    else return <InputNumber maxLength="18" value={record.weight} style={{ width: '100%' }} onChange={this.refreshInputNumber.bind(this, record.id, 'weight', 'normal')} />
                }
            },
            {
                title: '件数', dataIndex: 'count', key: 'count', width: '25%',
                render: (text, record, index) => {
                    if (disabled) return <span>{record.count}</span>
                    else return <InputNumber maxLength="11" value={record.count} style={{ width: '100%' }} onChange={this.refreshInputNumber.bind(this, record.id, 'count', 'normal')} />
                }
            }
        ];
        if (!disabled) normalColumns.push({
            key: 'delete', width: '10%', render: (text, record, index) => {
                return <Button type="primary" icon="delete" style={{ marginRight: 5 }} size={'small'} onClick={this.onDelete.bind(this, record.id, "normal")} />
            }
        })
        return normalColumns;
    }


    getPayColumns = (disabled) => {
        let payColumns = [
            {
                title: '重量(KGS)', dataIndex: 'weight', key: 'weight', width: '45%', render: (text, record, index) => {
                if (disabled) return <span>{record.weight}</span>
                else return <InputNumber maxLength="18" value={record.weight} style={{ width: '96%' }} onChange={this.refreshInputNumber.bind(this, record.id, 'weight', 'pay')} />
            }
            },
            {
                title: '件数', dataIndex: 'count', key: 'count', width: '45%', render: (text, record, index) => {
                if (disabled) return <span>{record.count}</span>
                else return <InputNumber maxLength="11" value={record.count} style={{ width: '100%' }} onChange={this.refreshInputNumber.bind(this, record.id, 'count', 'pay')} />
            }
            }
        ];
        if (!disabled) payColumns.push({
            key: 'delete', width: '10%', render: (text, record, index) => {
                return <Button type="primary" icon="delete" style={{ marginRight: 5 }} size={'small'} onClick={this.onDelete.bind(this, record.id, "pay")} />
            }
        })
        return payColumns;
    }


    render() {
        const { getFieldDecorator } = this.props.form;
        let dataSource = this.props.logisticsOrder.dataSource.declare ? this.props.logisticsOrder.dataSource.declare : {};

        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 14 } };
        let declareBillUrl = dataSource.declareBillUrl ? dataSource.declareBillUrl : undefined;
        let passNoticeUrl = dataSource.passNoticeUrl ? dataSource.passNoticeUrl : undefined;
        let otherUrl = dataSource.otherUrl ? dataSource.otherUrl : undefined;
        let module = "logistics";

        const divWithOutBorderBottom = {
            display: 'flex',
            borderRight: '1px solid #e9e9e9',
            borderLeft: '1px solid #e9e9e9',
            borderTop: '1px solid #e9e9e9',
            borderSpacing: 0,
            lineHeight: 4.2,
            textAlign: 'left'
        }

        return (
            <div>
                <Form>
                    <Tabs tabPosition={'top'}>
                        <TabPane tab="制定报关计划" key="1">
                            <div style={{ width: '88%', marginLeft: 50 }}>
                                <div style={{ textAlign: 'center' }}>
                                    <div><span><b><font size="4">广州瀚森乐达供应链管理有限公司——报关计划</font></b></span></div>
                                    <div style={{ marginTop: 10 }}><span><font size="2">地址: 广州市海珠区后滘镇后滘西大街139号鲁思湖畔空间创意园B1-207室</font></span>
                                        <span style={{ marginLeft: 50 }}>TEL: 020-87512605-813</span>
                                    </div>
                                </div>
                                <div style={{ textAlign: 'left', marginTop: 10, marginBottom: 10 }}>
                                    <div><span>TO: {dataSource.declareSupplierName}</span></div>
                                    <div style={{ marginTop: 10 }}><span>FM: {dataSource.gdUser ? dataSource.gdUser + "/" : null}{dataSource.gdTelephone}</span></div>
                                    {/* <div style={{ marginTop: 10 }}><span>SO号: {dataSource.soNo}</span></div> */}
                                    <div style={{ marginTop: 10 }}><span>柜型/柜量: {dataSource.size20gp ? dataSource.size20gp + "*20GP" : null}{dataSource.weight20gp ? dataSource.weight20gp + "KGS" : null}&nbsp;&nbsp;&nbsp;
                                        {dataSource.size40gp ? dataSource.size40gp + "*40GP" : null}{dataSource.weight40gp ? dataSource.weight40gp + "KGS" : null}&nbsp;&nbsp;&nbsp;
                                        {dataSource.size40hq ? dataSource.size40hq + "*40HQ" : null}{dataSource.weight40hq ? dataSource.weight40hq + "KGS" : null}</span></div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '100%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>报关行 &nbsp;&nbsp;
                                            <span>
                                                {getFieldDecorator('customsBroker', {
                                                    initialValue: dataSource.customsBroker
                                                })(
                                                    <Input maxLength="300" disabled={this.props.disabled} style={{ width: '90%', marginBottom: 5, marginLeft: 24 }} />
                                                )}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '100%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>出口码头 &nbsp;&nbsp;
                                            <span>
                                                {getFieldDecorator('exportWharf', {
                                                    initialValue: dataSource.exportWharf
                                                })(
                                                    <Input maxLength="300" disabled={this.props.disabled} style={{ width: '90%', marginBottom: 5 }} />
                                                )}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '100%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>报关要求 &nbsp;&nbsp;
                                            <span>
                                                {getFieldDecorator('declareRequire', {
                                                    initialValue: dataSource.declareRequire
                                                })(
                                                    <Input maxLength="300" disabled={this.props.disabled} style={{ width: '90%', marginBottom: 5 }} />
                                                )}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '90%', marginLeft: 10 }}>
                                        <div>报关方式 &nbsp;&nbsp;
                                            <span>
                                                {getFieldDecorator('declareType', {
                                                    initialValue: dataSource.declareType
                                                })(
                                                    <RadioGroup style={{ width: '60%' }}  disabled={this.props.disabled}>
                                                        <Radio value="1">国际中转</Radio>
                                                        <Radio value="2">内河转关</Radio>
                                                        <Radio value="3">一关通</Radio>
                                                    </RadioGroup>
                                                )}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '8%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>提单 </div>
                                    <div style={{ width: '46%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>总毛重 &nbsp;&nbsp; <span>
                                            {getFieldDecorator('totalWeight', {
                                                initialValue: dataSource.totalWeight
                                            })(
                                                <InputNumber maxLength="18" disabled={this.props.disabled} style={{ width: '75%', marginBottom: 5 }} />
                                            )}KGS
                                        </span>
                                        </div>
                                    </div>
                                    <div style={{ width: '46%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>总件数 &nbsp;&nbsp; <span>
                                            {getFieldDecorator('totalNum', {
                                                initialValue: dataSource.totalNum
                                            })(
                                                <InputNumber maxLength="18" disabled={this.props.disabled} style={{ width: '80%', marginBottom: 5 }} />
                                            )}
                                        </span>
                                        </div>
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '20%', textAlign: 'center', borderRight: '1px solid #e9e9e9' }}>
                                        {(this.props.disabled) ? <span>{"正常单报关(" + this.state.normalDeclareExt.length + ")"}</span> :
                                            <Button type="primary" icon="plus" size={'small'} onClick={this.onAdd.bind(this, "normal")}>{"正常单报关(" + this.state.normalDeclareExt.length + ")"}</Button>}
                                    </div>
                                    <div style={{ width: '100%', display: this.state.normalDeclareExt.length > 0 ? 'inline-block' : 'none' }}>
                                        <Table rowKey='id' bordered={false} className="customTableSmall"
                                               loading={this.props.loading} dataSource={this.state.normalDeclareExt}
                                               columns={this.getNormalColumns(this.props.disabled)}
                                               size={'small'} pagination={false} />
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '20%', textAlign: 'center', borderRight: '1px solid #e9e9e9' }}>
                                        {(this.props.disabled) ? <span>{"买单报关(" + this.state.payDeclareExt.length + ")"}</span> :
                                            <Button type="primary" icon="plus" size={'small'} onClick={this.onAdd.bind(this, "pay")}>{"买单报关(" + this.state.payDeclareExt.length + ")"}</Button>}
                                    </div>
                                    <div style={{ width: '100%', display: this.state.payDeclareExt.length > 0 ? 'inline-block' : 'none' }}>
                                        <Table rowKey='id' bordered={false} className="customTableSmall"
                                               loading={this.props.loading} dataSource={this.state.payDeclareExt}
                                               columns={this.getPayColumns(this.props.disabled)}
                                               size={'small'} pagination={false} />
                                    </div>
                                </div>

                                <div style={divWithOutBorderBottom}>
                                    <div style={{ marginLeft: 248 }}><font size="2">注意: 正常单报关件数+买单报关件数=提单总件数<br />
                                        <div style={{ marginLeft: 30 }}>正常单报关重量+买单报关重量=提单总毛重</div></font></div>
                                </div>
                                <div style={Object.assign({}, { borderBottom: '1px solid #e9e9e9', marginBottom: 20 }, divWithOutBorderBottom)}>
                                    <div style={{ width: '50%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>正常单报关费 &nbsp; <span>
                                            {getFieldDecorator('normalDeclareFee', {
                                                initialValue: dataSource.normalDeclareFee
                                            })(
                                                <Input maxLength="11" disabled={this.props.disabled} style={{ width: '76%', marginBottom: 5 }} />
                                            )}
                                        </span>
                                        </div>
                                    </div>
                                    <div style={{ width: '50%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>买单报关费 &nbsp; <span>
                                            {getFieldDecorator('payBillDeclareFee', {
                                                initialValue: dataSource.payBillDeclareFee
                                            })(
                                                <Input maxLength="11" disabled={this.props.disabled} style={{ width: '78%', marginBottom: 5 }} />
                                            )}
                                        </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </TabPane>
                    </Tabs>

                    <Tabs tabPosition={'top'}>
                        <TabPane tab="报关凭证" key="1">
                            <Row>
                                <Col span={12}>
                                    <FormItem {...formItemLayout} label="报关底单" hasFeedback>
                                        <SingleDragger url={declareBillUrl} ref="declareBillUrl" dataSource={dataSource}
                                                       module={module}
                                                       disabled={this.props.disabled}/>
                                    </FormItem>
                                </Col>
                                <Col span={12}>
                                    <FormItem {...formItemLayout} label="放行通知书" hasFeedback>
                                        <SingleDragger url={passNoticeUrl} ref="passNoticeUrl" dataSource={dataSource}
                                                       module={module}
                                                       disabled={this.props.disabled}/>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <FormItem {...formItemLayout} label="其他资料" hasFeedback>
                                        <SingleDragger url={otherUrl} ref="otherUrl" dataSource={dataSource}
                                                       module={module}
                                                       disabled={this.props.disabled}/>
                                    </FormItem>
                                </Col>
                            </Row>
                        </TabPane>
                    </Tabs>
                </Form>
            </div>
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.logisticsOrder, logisticsOrder: state.logisticsOrder,
    };
}

export default connect(mapStateToProps)(lgOdDeclare);